//
//  SearchViewController.m
//  TasteEnjoy
//
//  Created by XuRui on 16/5/5.
//  Copyright © 2016年 XuRui. All rights reserved.
//

#import "SearchViewController.h"

@interface SearchViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, XrLayoutItemHeightDelegate, UISearchBarDelegate, UISearchResultsUpdating>

@property (nonatomic, retain) BaseCollectionView *collectionView;  /**< collection */

@property (nonatomic, retain) NSMutableArray *arrData;


@property (nonatomic, retain) NSString *heightStr;// 关键字高亮

@property (nonatomic, retain) UISearchController *seachVC;

@end

@implementation SearchViewController

#pragma mark - ------------ 内存管理 ---------------
- (void)dealloc
{
    _collectionView.delegate = nil;
    _collectionView.dataSource = nil;
    [_collectionView release];
    [_arrData release];
    [_heightStr release];
    [_seachVC release];
    [super dealloc];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self creatSearchVC];
    [self creatCollectionView];
}

#pragma mark - ------------ 在视图消失中 ---------------

//将UISearchController移除, 否则切换到下一个View中, 搜索框仍然会有短暂的存在.
- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    if (self.seachVC.active) {
        
        self.seachVC.active = NO;
        
        [self.seachVC.searchBar removeFromSuperview];
    }
}


#pragma mark -  判断emoji表情
-(BOOL)stringContainsEmoji:(NSString *)string {
    __block BOOL returnValue = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
     ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
         
         const unichar hs = [substring characterAtIndex:0];
         // surrogate pair
         if (0xd800 <= hs && hs <= 0xdbff) {
             if (substring.length > 1) {
                 const unichar ls = [substring characterAtIndex:1];
                 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                 if (0x1d000 <= uc && uc <= 0x1f77f) {
                     returnValue = YES;
                 }
             }
         } else if (substring.length > 1) {
             const unichar ls = [substring characterAtIndex:1];
             if (ls == 0x20e3) {
                 returnValue = YES;
             }
             
         } else {
             // non surrogate
             if (0x2100 <= hs && hs <= 0x27ff) {
                 returnValue = YES;
             } else if (0x2B05 <= hs && hs <= 0x2b07) {
                 returnValue = YES;
             } else if (0x2934 <= hs && hs <= 0x2935) {
                 returnValue = YES;
             } else if (0x3297 <= hs && hs <= 0x3299) {
                 returnValue = YES;
             } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                 returnValue = YES;
             }
         }
     }];
    
    return returnValue;
}


#pragma mark - ------------ 创建搜索视图 ---------------
- (void)creatSearchVC
{
    
    self.seachVC = [[UISearchController alloc]initWithSearchResultsController:nil];
    _seachVC.dimsBackgroundDuringPresentation = NO; /**< 屏幕变灰 yes时tabView 不能下拉 */
    _seachVC.hidesNavigationBarDuringPresentation = NO;  /**< 点击搜索框时 隐藏导航栏 */
    _seachVC.searchBar.placeholder = @"搜索感兴趣的内容";
    _seachVC.searchBar.searchBarStyle = UISearchBarStyleMinimal;
    _seachVC.searchResultsUpdater = self;
    [_seachVC.searchBar sizeToFit];
    
    //改搜索字颜色
    UITextField *text = [_seachVC.searchBar valueForKey:@"_searchField"];
    text.textColor = [UIColor whiteColor];
    _seachVC.active = YES;
    self.navigationItem.titleView = _seachVC.searchBar;
    [_seachVC release];
}


#pragma mark - ------------ 只要一搜索就会走的方法 ---------------
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    
    
    self.heightStr = self.seachVC.searchBar.text;
    
    if ([_heightStr containsString:@" "]) {
      
//         判断如果有空格不执行
//         没有执行以下程序
//        不写这个判断 打空格就会崩溃
    }else{
        
        
       [self dataHandle];
        
     
    }
    if ([self stringContainsEmoji:_heightStr]) {
        
        //判断是否包括 表情
        UIAlertController *aletr = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"对不起数据里无%@", _heightStr] message:@"请重新输入" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:aletr animated:YES completion:^{
           
        }];

        // 提示框延迟消失
        [self performSelector:@selector(dismiss) withObject:aletr afterDelay:1];
    }
}

- (void)dismiss{
  
    [self dismissViewControllerAnimated:YES completion:^{
        
        self.seachVC.searchBar.text = nil;
       // [self.view endEditing:YES];

    }];
}





#pragma mark - ------------ 数据解析 ---------------
- (void)dataHandle
{

    //搜索的 必须转码
    NSString *chinese = [_heightStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:_heightStr]];
    
    NSString *str = @"http://203.80.144.212/napi/blog/list/by_search/?screen_width=1080&app_version=74&start=0&locale=zh&kw=%E7%AB%8B%E5%A4%8F&screen_height=1920&platform_version=6.0.1&__domain=www.duitang.com&platform_name=Android&device_platform=MI%2B4LTE&include_fields=sender%2Calbum%2Cicon_url%2Creply_count%2Clike_count&app_code=nayutas";
    NSString *url = [str stringByReplacingOccurrencesOfString:@"kw=%E7%AB%8B%E5%A4%8F" withString:[NSString stringWithFormat:@"kw=%@",chinese]];
  
    
    [XrDataParse GETWithURL:url par:nil success:^(id responseObject) {
       
        NSArray *arr = responseObject[@"data"][@"object_list"];
        
        self.arrData = [FindDeatilModel modelHandleWithArrar:arr];
        
        [_collectionView reloadData];

    } filed:^(NSError *error) {
        
        NSLog(@"搜索数据解析失败");
    }];
    

}



#pragma mark - ------------ 瀑布流layout---------------
- (void)creatCollectionView
{
    
    // 自定义layout
    XrLayout *layout = [[XrLayout alloc] init];
    //列数
    layout.columCounts = 2;
    
    //列间距
    layout.columSpace = 10;
    //行间距
    layout.rowSpace = 20;
    //边距
    layout.edgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
    //代理
    layout.delegate = self;
    
    
    //下方collectionView
    self.collectionView = [[BaseCollectionView alloc]initWithFrame:SCREEN_BOUNDS collectionViewLayout:layout];
    //collection代理
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.showsVerticalScrollIndicator = YES;
    //collection背景色
    _collectionView.backgroundColor = GrayLight;
    [self.view addSubview:_collectionView];
    [_collectionView registerClass:[FindDetailCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    
    [layout release];
    [_collectionView release];
    
}

#pragma mark - ------------ 赋值 ---------------
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    FindDetailCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    if (_arrData.count != 0) {
        
        cell.backgroundColor = [UIColor whiteColor];
        //cell加个阴影
        cell.layer.shadowOffset = CGSizeMake(0.1, 0.1);
        cell.layer.shadowOpacity = 0.3;
        cell.layer.shadowRadius = 1;
        FindDeatilModel *m = _arrData[indexPath.row];
        
        cell.model = m;
        //高亮字
        NSMutableAttributedString *textRed = [[NSMutableAttributedString alloc]initWithString:m.msg];
        
        //取范围
        NSRange range = [m.msg rangeOfString:_heightStr];
        [textRed setAttributes:@{NSForegroundColorAttributeName: [UIColor redColor], NSFontAttributeName: [UIFont systemFontOfSize:20]} range:range];
        cell.labelContent.attributedText = textRed;
        
        
    }
    return cell;
}


#pragma mark - ------------ 点击跳转详情 ---------------
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    DetailDetailViewController *detail = [[DetailDetailViewController alloc]init];
    FindDeatilModel *m = _arrData[indexPath.item];
    
    detail.detailID = m.iid.stringValue;
    [self.navigationController pushViewController:detail animated:YES];
    [detail release];
    
}



#pragma mark - ------------ 返回个数 ---------------
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    return _arrData.count;
    
}

#pragma mark - ------------ 设置高度 ---------------
- (CGFloat)layout:(XrLayout *)layout heightForItemAtIndexPath:(NSIndexPath *)indexPath width:(CGFloat)width
{
    
    FindDeatilModel *m = _arrData[indexPath.item];
    //图片高度
    CGFloat imgH = width * m.height.doubleValue / m.width.doubleValue;
    //文字高度
    CGFloat h1 = [FindDetailCollectionViewCell heightWithText:m.msg];
    //返回行数
    if (h1 >= 15.51 * 6) {
        h1 = 15.51 * 6;
    }
    
    // 每个cell的高度 = 图片高度 和 文本高度  + 其他控件高度(80)
    return imgH + h1 + 106 ;
    
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
